import React, { useState, useMemo } from 'react';
import PropTypes from 'prop-types';
import { Icon, Spin, Button, Modal, Typography, Tooltip, Tag, message, Empty } from 'antd';
import { history } from 'umi'
import authHelper from '@/utils/auth/helper';
import { eventTrack } from '@/utils/track';
import IconPro from '@/components/IconPro';
import { useRequest } from '@/hooks';
import Avatar from '../avatar';
import styles from './index.less';
import { getEmployeesByCode2 } from '../../services';

const { checkCode } = authHelper;
const { Paragraph } = Typography;

// 手机号码的处理
const getMobile = result => {
    if (result.length <= 3) {
        return result;
    }
    const middleNul = Math.ceil(result.length / 3);
    let stars = '';

    for (let index = 0; index < middleNul; index += 1) {
        stars += '*';
    }
    return `${result.slice(0, middleNul)}${stars}${result.slice(2 * middleNul, result.length)}`;
};

const eventTrackFn = async data => {
    await eventTrack({
        eventName: 'personnel_management_organization_view_context_click',
        pageName: 'personnel_management_organization',
        eventProps: {
            click_context: `${data.administrativeOrganizationName}-${data.organizationName}-${data.employeeName}`
        }
    });
};

/*
 * employeeInfo 如果没有值, 那就内部获取最新的数据. 如果没有值, 就通过 organizationCode 和 employeeCode 获取最新值.
 * 两者通过 employeeName 字段来判断是否传的是完整对象
 */
const Employee = ({
    organizationCode,
    employeeCode,
    employeeInfo,
    organizationType,
    noSubordinates,
    callback,
    ...otherProps
}) => {
    const [hideMobile, setHideMobile] = useState(true);
    const { data: employee = employeeInfo, loading } = useRequest(
        () =>
            getEmployeesByCode2({
                organizationCode,
                employeeCode,
                queryOrgLeaderByOrganizationCode: true
            }),
        {
            ready: !employeeInfo && !!organizationCode,
            formatResult: res => {
                if (res) {
                    const { code, data, msg } = res;
                    if (code === 10000) {
                        eventTrackFn(Array.isArray(data) ? data[0] || {} : data);
                        return Array.isArray(data) ? data[0] || {} : data;
                    }
                    message.error(msg);
                }
                return undefined;
            }
        }
    );

    const {
        employeeName,
        avatarFile = [],
        dutyAlias,
        rankValue,
        email,
        mobile,
        organizationName,
        administrativeOrganizationName,
        leaderEmployees,
        chargeNumber,
        dutyType
    } = employee || {};

    const phone = useMemo(() => {
        const result = mobile;
        if (result && hideMobile) {
            return getMobile(result);
        }
        return result;
    }, [hideMobile, mobile]);

    const handlerClick = () => {
        setHideMobile(state => !state);
    };

    const renderOrganizationNameDom = React.useMemo(() => {
        if (organizationName) {
            return (
                <>
                    {organizationName}
                    {dutyType === 0 ? (
                        <Tag color="blue" style={{ marginLeft: 8 }}>
                            兼
                        </Tag>
                    ) : null}
                </>
            );
        }
        return '--';
    }, [dutyType, organizationName]);

    return (
        <div className={styles.employeeWrapper} {...otherProps}>
            {loading && (
                <div className={styles.loading}>
                    <Spin />
                </div>
            )}
            {!loading && !employee && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
            {employee && (
                <>
                    <div className={styles.headerPanel}>
                        <Avatar size={35} src={avatarFile.length > 0 && avatarFile[0]?.url} alt={employeeName} />
                        <div className={styles.userPanel}>
                            <div className={styles.employeeName}>
                                {employeeName}
                                <small title={`${dutyAlias}${rankValue ? '/' : null}${rankValue}`}>
                                    {dutyAlias}
                                    {rankValue ? '/' : null}
                                    {rankValue}
                                </small>
                            </div>
                            {checkCode('office:orgs:employee:detail') && (
                                <Tooltip placement="top" title="查看个人档案">
                                    <IconPro.Button
                                        className={styles.detailLink}
                                        dark
                                        icon="user"
                                        onClick={async () => {
                                            await eventTrack({
                                                eventName: 'personnel_management_organization_view_context_click',
                                                pageName: 'personnel_management_organization',
                                                eventProps: {
                                                    click_context: `${administrativeOrganizationName -
                                                        organizationName -
                                                        employeeName} 查看详情`
                                                }
                                            });
                                            // 离开页面时需要隐藏气泡框
                                            const employeePopover = document.querySelector(
                                                '.employeePopover:not(.ant-popover-hidden)'
                                            );
                                            if (employeePopover) {
                                                employeePopover.classList.add('ant-popover-hidden');
                                            }
                                            Modal.destroyAll();
                                            history.push({
                                                pathname:
                                                    '/office/personnelManagement/organization/employeeList/detail',
                                                query: {
                                                    employeeCode: employee?.employeeCode,
                                                    dutyCode: employee?.dutyCode
                                                }
                                            });
                                            if (callback) {
                                                callback();
                                            }
                                        }}
                                    />
                                </Tooltip>
                            )}
                        </div>
                    </div>
                    <div className={styles.orgPanel}>
                        <div>
                            <span>组织机构</span> {renderOrganizationNameDom}
                        </div>
                        <div>
                            <span>行政机构</span> {administrativeOrganizationName || '--'}
                        </div>
                        {organizationType === 1 ? null : (
                            <div>
                                <span>上级</span>
                                {leaderEmployees?.length ? leaderEmployees.map(i => i.employeeName).join('，') : '--'}
                            </div>
                        )}
                        {organizationType === 1 || noSubordinates ? null : (
                            <div>
                                <span>下属</span>
                                <span className={styles.subordinates}>{chargeNumber || '--'}</span>
                            </div>
                        )}
                    </div>
                    <div className={styles.contactPanel}>
                        <div>
                            <span>手机</span>
                            <span className={styles.phone}>{phone || '--'}</span>
                            {phone &&
                                (hideMobile ? (
                                    <Icon style={{ color: '#bcc1cd' }} type="eye" onClick={handlerClick} />
                                ) : (
                                    <Icon style={{ color: '#bcc1cd' }} type="eye-invisible" onClick={handlerClick} />
                                ))}
                        </div>
                        <div>
                            <span>邮箱</span>
                            {email ? (
                                <div className={styles.copyEmail}>
                                    <Paragraph style={{ marginBottom: '0' }} copyable>
                                        {email}
                                    </Paragraph>
                                </div>
                            ) : (
                                '--'
                            )}
                        </div>
                    </div>
                    <div className={styles.sendMessage}>
                        <Button type="primary" disabled block className={styles.sendMessageButton}>
                            发送消息
                        </Button>
                    </div>
                </>
            )}
        </div>
    );
};

Employee.propTypes = {
    organizationCode: PropTypes.string,
    employeeCode: PropTypes.string,
    employeeInfo: PropTypes.object,
    organizationType: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
    noSubordinates: PropTypes.bool
};
Employee.defaultProps = {
    organizationCode: null,
    employeeCode: null,
    employeeInfo: null,
    noSubordinates: false
};

export default Employee;
